package com.dao;

import com.bean.User;
import com.util.DBHelper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {
    /**
     * 注册方法
     * 根据传入的 User，像数据库插入一条数据
     */
    public void regist(User user) throws SQLException, ClassNotFoundException {
        String sql = "insert into users (user_username, user_password, user_gender, user_email) values (?, ?, ?, ?)";

        try (Connection connection = DBHelper.getConnection();
             PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setString(1, user.getUsername());
            statement.setString(2, user.getPassword());
            statement.setString(3, user.getGender());
            statement.setString(4, user.getEmail());
            statement.executeUpdate();
        }
    }

    public User get (String username, String password) throws SQLException, ClassNotFoundException {
        String sql = "select * from users where user_username = ? and user_password = ?";

        try (Connection connection = DBHelper.getConnection();
            PreparedStatement statement = connection.prepareStatement(sql)){
            statement.setString(1, username);
            statement.setString(2, password);

            try (ResultSet resultSet = statement.executeQuery()){
                // 数据查到了，说明了用户名和密码是对的，那么封装返回
                if (resultSet.next()) {
                    String gender = resultSet.getString(1);

                    User user = new User();
                    user.setUsername(username);
                    user.setPassword(password);
                    user.setGender(gender);
                    return user;
                } else {
                    // 如果没有查到，返回 null，说明用户名或密码错误
                    return null;
                }
            }
        }
    }
}
